<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" title="登录">
      <template #left>
        <!-- 后退上一页:  $router.back() 或 $router.go(-1) -->
        <van-icon name="cross" @click="$router.back()" />
      </template>
    </van-nav-bar>
    <!-- /导航栏 -->
    <!-- 登录表单 -->
    <van-form ref="LoginForm" @submit="onSubmit">
      <van-field
        name="mobile"
        placeholder="请输入用户名"
        clearable
        v-model="user.mobile"
        :rules="userFormRules.mobile"
        maxlength="11"
      >
        <template #left-icon>
          <i class="toutiao toutiao-shouji"></i>
        </template>
      </van-field>
      <van-field
        type="number"
        name="code"
        placeholder="请输入密码"
        clearable
        v-model="user.code"
        :rules="userFormRules.code"
        maxlength="6"
      >
        <template #left-icon>
          <i class="toutiao toutiao-yanzhengma"></i>
        </template>

        <template #button>
          <van-count-down
            v-if="isCountDownShow"
            :time="time"
            format=" ss s"
            @finish="isCountDownShow = false"
          />
          <van-button
            v-else
            class="send-sms-btn"
            round
            size="small"
            native-type="button"
            type="default"
            @click="onSendSms"
          >
            发送验证码
          </van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button block type="info" native-type="submit" class="login-btn"
          >登录</van-button
        >
      </div>
    </van-form>

  </div>
</template>

<script>
import { login, sendSms } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      // 验证规则对象
      userFormRules: {
        mobile: [
          { required: true, message: '手机号不能为空！' },
          {
            pattern: /^1[3|5||6|7|8|9]\d{9}$/,
            message: '请输入正确的手机号！'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空！' },
          {
            pattern: /^\d{6}$/,
            message: '请输入正确的验证码！'
          }
        ]
      },
      time: 6 * 1000, // 倒计时时间
      isCountDownShow: false // 是否显示倒计时
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    ...mapMutations(['setUser']),
    async onSubmit (values) {
      // 获取表单数据
      const user = this.user
      this.$toast.loading({
        duration: 0, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: '登录中...' // 提示消息
      })

      // 发送请求,实现登录
      try {
        const res = await login(user)
        console.log(res)
        this.$toast.success('登录成功!')
        this.$router.push('/')
        //  将用户数据存储到vuex中
        this.setUser(res.data)
      } catch (err) {
        console.log(err)
        if (err.response.status === 400) {
          this.$toast.fail('手机号或验证码错误')
        } else {
          this.$toast.fail('登录失败，请稍后重试', err)
        }
      }
    },
    async onSendSms () {
      // 验证手机号是否正确
      try {
        await this.$refs.LoginForm.validate('mobile')
      } catch (error) {
        return console.log('手机号验证失败！')
      }
      // 2. 验证通过，显示倒计时
      this.isCountDownShow = true
      // 3 发送验证码
      try {
        await sendSms(this.user.mobile)
        this.$toast('发送成功')
        this.user.code = '246810'
      } catch (err) {
        // 发送失败，关闭倒计时，显示发送按钮
        this.isCountDownShow = false
        if (err.response.status === 429) {
          this.$toast('发送太频繁了，请稍后重试')
        } else {
          this.$toast('发送失败，请稍后重试')
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  .toutiao {
    font-size: 37px;
    color: #666;
  }
  .send-sms-btn {
    // width: 160px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }
}
</style>
